//
//  XKFinanceViewController.m
//  XKJY
//
//  Created by xuyaguang on 2017/1/10.
//  Copyright © 2017年 xiaokang100. All rights reserved.
//

#import "AppDelegate.h"
#import "XKHomeViewController.h"
#import "XKHomeHeaderView.h"            // 首页banner图和WOS最新价

#import "XKHomeCollectionViewLayout.h"  // Layout布局
#import "XKHomeFunctionCell.h"          // 四个单元格
#import "XKHomeNewsCell.h"              // 最新动态单元格
#import "XKHomeHeaderReusableView.h"    // CollectionView可重用HeaderView
#import "XKHomeFooterReusableView.h"    // CollectionView可重用FooterView
#import "XKHomeClearReusableView.h"     // CollectionView空的可重用HeaderView

#import "XKRechargeController.h"        // 充值
#import "XKDrawMoneyController.h"       // 提现
#import "XKSupportController.h"         // 帮助中心
#import "XKCertificationController.h"   // 实名认证
#import "XKNewsModel.h"                 // 资讯模型
#import "Data.h"                        // 资讯数据
#import "XKNewsHtmlController.h"        // 资讯详情页



static NSString *const XKHomeFunctionCellReuseIdentifier        = @"XKHomeFunctionCellReuseIdentifier";
static NSString *const XKHomeNewsCellReuseIdentifier            = @"XKHomeNewsCellReuseIdentifier";
static NSString *const XKHomeHeaderReusableViewReuseIdentifier  = @"XKHomeHeaderReusableViewReuseIdentifier";
static NSString *const XKHomeFooterReusableViewReuseIdentifier  = @"XKHomeFooterReusableViewReuseIdentifier";
static NSString *const XKHomeClearReusableViewReuseIdentifier   = @"XKHomeClearReusableViewReuseIdentifier";

@interface XKHomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource, XKHomeCollectionViewLayoutDelegate, XKHomeHeaderViewDelegate, UIAlertViewDelegate>


@property (nonatomic, strong) UITableView       *tableView;
@property (nonatomic, strong) XKHomeHeaderView  *headerView;
@property (nonatomic, strong) UICollectionView  *collectionView;
@property (nonatomic, strong) NSTimer           *timer;
@property (nonatomic, strong) NSArray<Data *>   *newsArray;

@end

@implementation XKHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadDataWithNotice];  // 加载数据
    [self creatSubviews];       // 创建子视图
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self loadWOSCurrentPrice];
    // 定时器刷新WOS最新价格
    @weakify(self);
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:@"myTimer" timeInterval:5.0 queue:nil repeats:YES actionOption:AbandonPreviousAction action:^{
        @strongify(self);
        [self loadWOSCurrentPrice];
    }];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:@"myTimer"];
}

#pragma mark - 创建子视图
- (void)creatSubviews {
    _headerView = [XKHomeHeaderView new];
    _headerView.delegate = self;
    
    XKHomeCollectionViewLayout *layout = [[XKHomeCollectionViewLayout alloc] init];
    layout.delegate = self;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.showsVerticalScrollIndicator = YES;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.backgroundColor = kBaseGrayColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataWithNotice];
    }];
    
    // CollectionViewCell复用
    [_collectionView registerClass:[XKHomeFunctionCell class]
        forCellWithReuseIdentifier:XKHomeFunctionCellReuseIdentifier];
    [_collectionView registerClass:[XKHomeNewsCell class]
        forCellWithReuseIdentifier:XKHomeNewsCellReuseIdentifier];
    
    // HeaderView或FooterView复用
    [_collectionView registerClass:[XKHomeHeaderReusableView class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
               withReuseIdentifier:XKHomeHeaderReusableViewReuseIdentifier];
    [_collectionView registerClass:[XKHomeFooterReusableView class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
               withReuseIdentifier:XKHomeFooterReusableViewReuseIdentifier];
    [_collectionView registerClass:[XKHomeClearReusableView class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
               withReuseIdentifier:XKHomeClearReusableViewReuseIdentifier];
    
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.collectionView];
    self.headerView.frame = CGRectMake(0, 0, Main_Width, 257*Scale_H);
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.headerView.mas_bottom);
        make.bottom.mas_equalTo(self.view).offset(-49);
    }];
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    } else {
        return self.newsArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:{
            XKHomeFunctionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XKHomeFunctionCellReuseIdentifier forIndexPath:indexPath];
            cell.imageName = [NSString stringWithFormat:@"home_functioncell_icon_%02zd",indexPath.item + 1];
            cell.titleName = @[@"充值",@"提现",@"通宝兑换",@"帮助中心"][indexPath.item];
            return cell;
        }; break;
            
        case 1:{
            XKHomeNewsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XKHomeNewsCellReuseIdentifier forIndexPath:indexPath];
            cell.imageName = self.newsArray[indexPath.item].pic;
            cell.titleName = self.newsArray[indexPath.item].title;
            cell.flag = indexPath.item;
            return cell;
        }; break;
            
        default:return [UICollectionViewCell new]; break;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        if (indexPath.section == 0) {
            XKHomeClearReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:XKHomeClearReusableViewReuseIdentifier forIndexPath:indexPath];
            return headerView;
        } else {
            XKHomeHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:XKHomeHeaderReusableViewReuseIdentifier forIndexPath:indexPath];
            @weakify(self);
            headerView.moreNewsBlock = ^(){
                @strongify(self);
                [self.tabBarController setSelectedIndex:2];
            };
            return headerView;
        }
        
    } else {
        XKHomeFooterReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:XKHomeFooterReusableViewReuseIdentifier forIndexPath:indexPath];
        return footerView;
    }
}




#pragma mark - ServiceLayoutDelegate
- (CGFloat)heightOfSectionFooterForIndexPath:(NSIndexPath *)indexPath {
    return 5*Scale_H;
}
- (CGFloat)heightOfSectionHeaderForIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 0.01;
    } else {
        return 40*Scale_H;
    }
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger item = indexPath.item;
    if (section == 0) {
        switch (item) {
            case 0:{
                [self verifyUserStatus] ? [self pushViewController:[XKRechargeController new] title:@"充值"] : @"";
            }; break;
            case 1:{
                [self verifyUserStatus] ? [self pushViewController:[XKDrawMoneyController new] title:@"提现"] : @"";
            }; break;
            case 2:{
                [SVProgressHUD showInfoWithStatus:@"孵化中..."];
            }; break;
            case 3:{
                XKSupportController *supportVC = [XKSupportController new];
                supportVC.urlString = [NSString stringWithFormat:@"%@%@",base_url,HelpCenter];
                [self pushViewController:supportVC title:@"帮助中心"];
            }; break;
            default:{
                
            }; break;
        }
    } else if (section == 1) {
        XKNewsHtmlController *htmlVC = [XKNewsHtmlController new];
        htmlVC.htmlString = self.newsArray[indexPath.item].content;
        [self pushViewController:htmlVC title:@"最新动态"];
    }
}




#pragma mark - 加载首页WOS最新价格
- (void)loadWOSCurrentPrice {
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
        return;
    }
    NSLog(@"请求WOS最新价");
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_WOSPrice parameters:@{} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        NSString *temp = [NSString stringWithFormat:@"%@",successDict[@"data"][@"new_price"]];
        NSString *currentPrice = (NOEmptyStr(temp)) ? [NSString changeNumberFormat:temp] : @"0.00";
        [UserDefaults setObject:currentPrice withKey:@"new_price"];
        self.headerView.currentPriceString = currentPrice;
        self.headerView.wosPriceStatus = [NSString stringWithFormat:@"%@",successDict[@"data"][@"new_price_status"]];
        self.headerView.refreshTimeString = [NSString getCurrentTimeStringWithFormatter:@"YYYY-MM-dd HH:mm"];
    } failureBlock:^(NSDictionary *dict){
        
    } errorBlock:^(NSError *error){
        
    }];
}


#pragma mark - 加载公告信息
- (void)loadDataWithNotice {
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_LatestNews parameters:@{} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        [self.collectionView.mj_footer endRefreshing];
        XKNewsModel *model = [XKNewsModel mj_objectWithKeyValues:successDict];
        self.newsArray = model.data;
        
        [self.collectionView reloadData];
        
    } failureBlock:^(NSDictionary *dict){
        @strongify(self);
        [self.collectionView.mj_footer endRefreshing];
    } errorBlock:^(NSError *error){
        @strongify(self);
        [self.collectionView.mj_footer endRefreshing];
    }];
}


#pragma mark - 验证用户实名状态
- (BOOL)verifyUserStatus {
    NSString *state = [UserDefaults objectWithKey:@"status"];
    if ([state isEqualToString:@"0"]) {
        [self pushViewController:[XKCertificationController new] title:nil];
        return NO;
    } else if ([state isEqualToString:@"2"]) {
        [SVProgressHUD showInfoWithStatus:@"实名认证中..."];
        return NO;
    } else if ([state isEqualToString:@"1"]){
        return YES;
    } else {
        return NO;
    }
}


#pragma mark - 点击banner图打开商城网站
- (void)pushToOfficialWebsite {
    if (SYSTEM_VERSION_LESS_THAN(@"10")) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.xiaokang100.com"]];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.xiaokang100.com"] options:@{} completionHandler:nil];
    }
}



#pragma mark - 控制器跳转
- (void)pushViewController:(UIViewController *)viewController title:(NSString *)title {
    if (title != nil) {
        viewController.navigationItem.title = title;
    }
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
